<template>
  <view class="app">
    <view class="main-box">
      <view class="form-box">
        <view class="form-item avatar-item">
          <text class="item-title">头像</text>
          /* #ifdef H5 */
          <view class="item-right" @click="nav.jump('/components/mt-cropper/mt-cropper')">
            <view class="w-12 h-12 mr-1">
              <image
                class="w-full h-full rd-100"
                mode="aspectFit"
                :src="form.avatar || config.custom.avatar"
                @error="form.avatar = config.custom.avatar"
              />
            </view>
            <u-icon class="right-icon" size="26" color="#b7b7b7" name="arrow-right"></u-icon>
          </view>
          /* #endif */ /* #ifdef MP-WEIXIN */
          <view class="item-right">
            <button
              class="btn-view flex items-center w-12 h-12 mr-1"
              open-type="chooseAvatar"
              @chooseavatar="getAvatar"
            >
              <image
                class="w-full h-full rd-100"
                mode="aspectFit"
                :src="form.avatar || config.custom.avatar"
                @error="form.avatar = config.custom.avatar"
              />
            </button>
            <u-icon class="right-icon" size="26" color="#b7b7b7" name="arrow-right"></u-icon>
          </view>
          /* #endif */
        </view>

        <view class="form-item">
          <text class="item-title">手机</text>
          <view class="item-right" @click="nav.jump('/pages/setting/change_phone')">
            <text class="mr-1">{{ fansStore.fansinfo.phone }}</text>
            <u-icon class="right-icon" size="26" color="#b7b7b7" name="arrow-right"></u-icon>
          </view>
        </view>
        <view class="form-item">
          <text class="item-title">昵称</text>
          <input
            type="nickname"
            :cursor-spacing="20"
            placeholder="请输入昵称"
            placeholder-class="input-placeholder"
            v-model="form.nickname"
            @change="getNickname"
          />
        </view>
        <view class="form-item">
          <text class="item-title">姓名</text>
          <input type="text" v-model="form.username" placeholder="请输入姓名" />
        </view>
      </view>
      <view class="form-box">
        <view class="form-item">
          <text class="item-title">注册时间</text>
          <text>{{ fansStore.fansinfo.created_at }}</text>
        </view>
      </view>
    </view>

    <view class="footer">
      <view class="submit-btn" @click="save()">
        <text class="ml-10rpx">提 交</text>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
  import { reactive } from 'vue';
  import { msg } from '@/utils/msg';
  import { setFans } from '@/api/fans';
  import { useFansStore } from '@/store/fans';
  import { report } from '@/utils/exception';
  import { onShow } from '@dcloudio/uni-app';
  import { uploadImgToServerByH5, uploadImgToServerByWeixin } from '@/common/upload';
  import { md5 } from 'js-md5';
  import { base64ToFile } from '@/utils/file';
  import { config } from '@/config/env';
  import { nav } from '@/utils/homer';

  const fansStore = useFansStore();
  const form = reactive<any>({
    avatar: fansStore.fansinfo.avatar,
    nickname: fansStore.fansinfo.nickname,
    username: fansStore.fansinfo.username,
  });

  const platform = uni.getSystemInfoSync().uniPlatform;
  let changeAvatar = false;

  // fansStore.fansinfo.token = '123'
  // fansStore.fansinfo.refresh_token = '456'

  /* #ifdef H5 */
  onShow(() => {
    uni.$once('updateAvatar', (data) => {
      changeAvatar = true;
      form.avatar = data;
    });
  });
  /* #endif */

  const getAvatar = (e: any) => {
    changeAvatar = true;
    form.avatar = e.detail.avatarUrl;
  };

  const getNickname = (e: any) => {
    form.nickname = e.detail.value;
  };

  // 提交
  const save = async () => {
    if (form.nickname === '' && fansStore.fansinfo.nickname !== '') {
      return msg.error('请输入昵称');
    }
    // if (form.username === '' && fansStore.fansinfo.username !== '') {
    //   return msg.error('请输入姓名');
    // }

    const udpateFileds: string[] = [];
    if (form.avatar !== '' && form.avatar != fansStore.fansinfo.avatar) {
      udpateFileds.push('avatar');
    }
    if (form.nickname !== '' && form.nickname != fansStore.fansinfo.nickname) {
      udpateFileds.push('nickname');
    }
    if (form.username !== '' && form.username != fansStore.fansinfo.username) {
      udpateFileds.push('username');
    }

    if (udpateFileds.length == 0) {
      msg.success('个人信息保存成功！', 1500);
      setTimeout(() => {
        nav.back();
      }, 1500);
      return;
    }

    if (changeAvatar) {
      let fileName: string;
      switch (platform) {
        case 'mp-weixin':
          fileName = form.avatar.substring(form.avatar.lastIndexOf('/') + 1);
          form.avatar = (await uploadImgToServerByWeixin(form.avatar, fileName)) as string;
          break;

        case 'web':
          fileName = md5(form.avatar) + '.png';
          let imgFile = base64ToFile(form.avatar, fileName);
          form.avatar = (await uploadImgToServerByH5(imgFile, fileName)) as string;
          break;
      }

      changeAvatar = false;
    }

    msg.loading();
    setFans(form)
      .then((res) => {
        if (res.data.status == 1) {
          udpateFileds.forEach((item) => {
            fansStore.fansinfo[item] = form[item];
          });
          fansStore.invite_poster = '';
        }
        msg.success('个人信息保存成功！', 1500);
        setTimeout(() => {
          nav.back();
        }, 1500);
      })
      .catch((err) => {
        report(err);
      });
  };
</script>

<style lang="scss" scoped>
  $fontSize: 28rpx;

  .main-box {
    margin: 25rpx;

    .form-box {
      padding: 0 25rpx;
      background: white;
      border-radius: 20rpx;
      margin-bottom: 20rpx;

      .form-item {
        display: flex;
        align-items: center;
        height: 100rpx;
        justify-content: space-between;

        &:not(:last-child) {
          border-bottom: 1rpx solid $borderColor;
        }

        .item-title {
          font-size: $fontSize;
          font-weight: 600;
          width: 120rpx;
          flex: none;
        }

        .item-right {
          display: flex;

          .right-icon {
            position: relative;
            top: 2rpx;
            left: 2rpx;
          }
        }

        input {
          font-size: $fontSize;
          margin-right: 10rpx;
          width: 100%;
          text-align: right;
        }
      }

      .avatar-item {
        height: 135rpx;
      }
    }
  }

  .footer {
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 100%;
    height: 110rpx;

    .submit-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 90%;
      font-size: 26rpx;
      font-weight: 600;
      color: white;
      margin: 0 auto;
      padding: 24rpx 0;
      border-radius: 50rpx;
      letter-spacing: 1rpx;
      background: linear-gradient(315deg, #429ff6, #394eea, #2664ef);
      box-shadow: rgba(29, 154, 244, 0.2) 0 5rpx 12rpx;
    }
  }
</style>
